package com.qk.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.dto.ClueDto;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.mapper.ClueMapper;
import com.qk.mapper.ClueTrackRecordMapper;
import com.qk.service.ClueService;
import com.qk.utils.CurrentUserHoler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private ClueMapper clueMapper;

    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;

    @Override
    public PageResult<Clue> selectList(ClueDto clueDto) {

        Page <Clue> p = this.baseMapper.selectClList(new Page<Clue>(clueDto.getPage(),clueDto.getPageSize()),clueDto);
        return new PageResult<>(p.getTotal(),p.getRecords());
    }

    @Override
    public Clue selectClById(Integer id) {
        return clueMapper.selectClById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateTrById(Clue clue) {
        //1.线索表更新 状态  更新时间
        clue.setStatus(3);
        clue.setUpdateTime(LocalDateTime.now());
        clueMapper.updateById(clue);

        //2.线索跟进表更新
        ClueTrackRecord  clueTrack = new ClueTrackRecord();

        clueTrack.setClueId(clue.getId());
        clueTrack.setUserId(CurrentUserHoler.getCurrentUser());
        clueTrack.setRecord(clue.getRecord());
        clueTrack.setSubject(clue.getSubject());
        clueTrack.setLevel(clue.getLevel());
        clueTrack.setNextTime(clue.getNextTime());
        clueTrack.setType(1);
        clueTrack.setCreateTime(LocalDateTime.now());


        clueTrackRecordMapper.insert(clueTrack);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateFalseById(Integer id, ClueDto clueDto) {
        Clue clue = new Clue();
        clue.setId(id);
        clue.setStatus(4);
        clue.setUpdateTime(LocalDateTime.now());
        clueMapper.updateById(clue);

        ClueTrackRecord clueTrack = new ClueTrackRecord();
        clueTrack.setClueId(id);
        clueTrack.setType(0);
        clueTrack.setUserId(CurrentUserHoler.getCurrentUser());
        clueTrack.setFalseReason(clueDto.getReason());
        clueTrack.setRecord(clueDto.getRemark());
        clueTrack.setCreateTime(LocalDateTime.now());
        clueTrackRecordMapper.insert(clueTrack);
    }
}
